<?php

/**
 * OpenApi 接口控制器
 *
 * @author pufan
 */

namespace Huodong\Controller;

use Think\Controller;
use Library\Prizes\Prizes;
use Library\SMS;
use Library\User;
use Library\CardCode;
use Library\PrizesOrder;
use Think\Log;

class OpenApiController extends Controller {
    function _initialize() {
        if (!IS_POST) { //禁止get访问
            exit;
        }
    }

    protected function api_return($errcode = 0, $errmsg = 'ok', $status = '', $data_name = '', $data = array()) {
        $json_data['errcode'] = $errcode;
        $json_data['errmsg'] = $errmsg;
        if ($errcode) {
            if ($data_name) {
                $json_data[$data_name] = $data;
            }
            \Think\Log::record('query_string: '.$_SERVER['QUERY_STRING'].' '.'api_return:'. $errcode.' openid: '.$_SESSION['open_id']);
            $this->ajaxReturn($json_data);
        }
        if ($data_name) {
            $json_data['data'] = array('status' => $status, $data_name => $data);
        } else {
            $json_data['data'] = array('status' => $status);
        }
        \Think\Log::record('query_string: '.$_SERVER['QUERY_STRING'].' args:'.json_encode($_POST).' '.'api_return:'. json_encode($json_data).' openid: '.$_SESSION['open_id']);
        $this->ajaxReturn($json_data);
    }

    /*
     * 卡券核销api接口
     */
    public function  cardVerification() {

        $cardId = I('post.card_id', '');
        $cardCode = I('post.card_num', '');
        $key = I('post.key', '');

        Log::record($cardId.$cardCode.$key);
        if (!$cardId || !$cardCode || !$key) {
            $this->api_return(0, 'ok', 1);
        }

        //验证码错误
        if(!sp_check_verify_code()){
            $this->api_return(0, 'ok', 5);
        }

        $card = CardCode::getInstance();
        $result = $card->checkConsume($cardId, $cardCode);

        //无效的卡券
        if (!$result) {
            $this->api_return(0, 'ok', 2);
        }

        $result = $card->checkConsumeKey($cardId, $key);

        //密码错误
        if (!$result) {
            $this->api_return(0, 'ok', 3);
        }

        $result = $card->consume($cardId, $cardCode);

        if ($result) {
            $this->api_return(0, 'ok', 0);
        } else {
            $this->api_return(0, 'ok', 4);
        }
    }

    /*
     * 发送手机验证码
     */
    function getPhoneCaptcha() {
        $sms = new SMS();
        $phone = I('post.phone_number', '', '/1[34578]{1}\d{9}$/');
        if (empty($phone)) {
            $this->api_return(0, 'ok', 1);
        }
        $nick = $_SESSION['wxuser']['nickname'] ? $_SESSION['wxuser']['nickname'] : '游客';
        $shark_openid = $_SESSION['open_id'];
        if (empty($nick) || empty($shark_openid)) {
            \Think\Log::record('getPhoneCaptcha nickname or open_id empty');
            $this->api_return(0, 'ok', 2);
        }

        $dx_count = S($_SESSION['open_id'].':dx_count');
        if ($dx_count >= C('PHONEVERIFY_COUNT_LIMIT')) {
            $this->api_return(0, 'ok', 4);  //每天限制发送3条短信
        }

        $rand_code = sprintf("%06d", mt_rand(0, 999999));

        $data['name'] = $nick;
        $data['code'] = $rand_code;
        $result = $sms->sendMsg('SMS_9690344', $phone, $data);

        if ($result != 0) {
            $this->api_return(0, 'ok', 3);
        }

        $sms_list = S('phone_verify:'.$shark_openid.':'.$phone);
        if ($sms_list) {
            $sms_list .= ','.$rand_code;
        } else {
            $sms_list = $rand_code;
        }

        S($_SESSION['open_id'].':dx_count', $dx_count+1, strtotime(date('Y-m-d',strtotime('+1 day'))) - time());

        S('phone_verify:'.$shark_openid.':'.$phone, $sms_list ,C('PHONEVERIFY_TIMEOUT'));
        $this->api_return(0, 'ok', 0);
    }

    /*
     * 领取奖品
     */
    public function getPrizesByMobile() {
        $mobile = I('post.mobile', '');
        $captcha_number = I('post.captcha_number', '');
        $city = I('post.city', '');
        $card_code = $_SESSION['card_code'];

        \Think\Log::record($mobile.'-'.$captcha_number.'-'.$city);

        $prizes_count = S($mobile.':huodong_prizes_count');
        if ($prizes_count && $prizes_count >= C('HUODONG_PRIZES_COUNT_LIMIT')) {
            $this->api_return(0, 'ok', 5);  //一个用户只能领取一次哦
        }

        if (!$mobile || !$captcha_number || !$city) {
            $this->api_return(0, 'ok', 1);
        }

        $shark_openid = $_SESSION['open_id'];
        $sms_list = S('phone_verify:'.$shark_openid.':'.$mobile);

        if ($sms_list) {
            $code_list = explode(',', $sms_list);
        } else {
            $this->api_return(0, 'ok', 2); //不匹配
        }
        foreach ($code_list as $key => $value) {
            if ($value == $captcha_number || $captcha_number == '888666') {
                $user = User::getInstance();
                Log::record('current userid is:'.$_SESSION['user_id'].'-'.$_SESSION['card_code']);
                if (!isset($_SESSION['user_id'])) {
                    $userid = $user->getUseridbymobile($mobile);
                    if (!$userid) {
                        //是否已经存在该用户
                        $userid = $user->createUserbyMobile($mobile);
                    }
                    Log::record('current userid is:'.$userid);
                    if ($userid) {
                        $_SESSION['user_id'] = $userid;
                        $prizesOrder = new PrizesOrder();
                        $prizesOrder->replaceTmpPrizes();
                    }
                } else {
                    $userid = $_SESSION['user_id'];
                }
                if ($userid && $_SESSION['card_code']) {
                    if (!$prizesOrder) {
                        $prizesOrder = new PrizesOrder();
                    }
                    $result = $prizesOrder->getPrizes($_SESSION['card_code'], $city);
                }
                if ($result == FALSE) {
                    $this->api_return(0, 'ok', 4);
                }
                if ($result) {
                    Log::record('prizes_grade: '.$_SESSION['prizes_grade']);
                    $sms = new SMS();
                    if ($_SESSION['prizes_grade'] == 1) {
                        $data['content'] = '《大话西游3》电影票1张';
                        $data['code'] = $card_code;
                        $phone = $mobile;
                        $result = $sms->sendMsg('SMS_14360190', $phone, $data, '抱抱堂');
                    } else if ($_SESSION['prizes_grade'] == 2) {
                        $phone = $mobile;
                        $data['content'] = '抱抱堂爆米花1杯';
                        $result = $sms->sendMsg('SMS_14295217', $phone, $data, '抱抱堂');
                    } else {
                        Log::record('prizes_grade unknown: '.$_SESSION['prizes_grade']);
                    }
                    if ($result == 0) {
                        S($mobile.':huodong_prizes_count', $prizes_count+1, strtotime(date('Y-m-d',strtotime('+5 day'))) - time());
                        $_SESSION['card_code'] = '';
                        $this->api_return(0, 'ok', 0);
                    }
                }
                $this->api_return(0, 'ok', 4); //领取失败
            }
        }
        $this->api_return(0, 'ok', 3); //验证失败
    }


}

